package com.kingsoft.miot.bridge.service.impl;

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.kingsoft.miot.bridge.pojo.SignAndVerify;
import com.kingsoft.miot.bridge.service.BaseService;
import com.kingsoft.miot.bridge.utils.ECDSAUtil;

/**
 * 基础服务
 * 
 * @author HUJIANQING
 *
 */
public class BaseServiceImpl implements BaseService {

	/**
	 * 创建请求参数
	 * @param groupId
	 * @param authUnitId
	 * @param privateKey
	 * @param method
	 * @param uri
	 * @param nonce
	 * @param data
	 * @return
	 */
	protected static List<NameValuePair> createParams(long groupId, long authUnitId, String privateKey, String method,
			String uri, String nonce, String data) {
		List<NameValuePair> params = new LinkedList<>();
		params.add(new BasicNameValuePair("_nonce", nonce));
		params.add(new BasicNameValuePair("_groupId", groupId + ""));
		params.add(new BasicNameValuePair("_authUnitId", authUnitId + ""));
		params.add(new BasicNameValuePair("_data", data));
		StringBuilder toSignTextBuilder = new StringBuilder();
		toSignTextBuilder.append(method).append("&").append(uri).append("&").append(data).append("&").append(nonce);
		String toSignText = toSignTextBuilder.toString();
		String sign = ECDSAUtil.signWithStr(toSignText.getBytes(), privateKey);
		params.add(new BasicNameValuePair("_signature", sign));
		return params;
	}
	
	
	/**
	 * ECDSA 离线验证
	 * 
	 * @param method
	 * @param url
	 * @param value
	 * @param nonceStr
	 * @param pubKey
	 * @param priKey
	 * @return 返回中间结果 ： sign以及是否验证
	 */
	protected static SignAndVerify verify(String method, String url, String data, String nonceStr, String pubKey,
			String priKey) {
		SignAndVerify signAndVerify = new SignAndVerify();
		try {
			StringBuilder toSignTextBuilder = new StringBuilder();
			toSignTextBuilder.append(method).append("&").append(url).append("&").append(data).append("&")
					.append(nonceStr);
			String toSignText = toSignTextBuilder.toString();
			String sign = ECDSAUtil.signWithStr(toSignText.getBytes(), priKey);
			signAndVerify.setSign(sign);
			byte[] basePubKey = Base64.decodeBase64(pubKey);
			// 待验证
//			boolean verify = ECDSAUtil.verify(toSignText.getBytes(), basePubKey, sign);
//			signAndVerify.setVerify(verify);
		} catch (Exception e) {
			signAndVerify.setVerify(false);
			return signAndVerify;
		}
		return signAndVerify;
	}
}
